package com.sysware.p2m;

import com.sysware.p2m.oracleclient.OracleClient;
import com.sysware.p2m.utils.DBPropertiesUtil;

import java.io.File;

public class OracleTool extends AbstracDBTool {

    /**
     * 创建用户指令
     */
    public static final String CMD_CREATE_USER = "create_user";

    /**
     * 删除用户指令
     */
    public static final String CMD_DROP_USER = "drop_user";

    /**
     * 执行SQL指令
     */
    public static final String CMD_EXECUTE_SQL = "execute_sql";

    /**
     * 清空用户数据库指令
     */
    public static final String CMD_DB_CLEAN = "db_clean";

    public static final String CMD_DB_BASELINE = "db_baseline";

    public static void main(String[] args) {
        if (args == null || args.length < 1) {
            return;
        }
        logger.info("main args:{}", args);
        if (validateProperties() != 1) {
            return;
        }

        try {
            cmdExecute(args[0]);
        }catch (RuntimeException e){
            logger.error(e.getLocalizedMessage());
            e.printStackTrace();
        }

    }

    public static void cmdExecute(String cmd) throws RuntimeException{
        OracleClient dbaOracleClient = new OracleClient(getConfigUrl(), getConfigDBAUser(), getConfigDBAPassword());
        OracleClient oracleClient = new OracleClient(getConfigUrl(), getConfigUser(), getConfigPassword());
        switch (cmd) {
            case CMD_CREATE_USER: {
                dbaOracleClient.createUser(getConfigUser(), getConfigPassword());
                break;
            }
            case CMD_DROP_USER: {
                dbaOracleClient.dropUser(getConfigUser());
                break;
            }
            case CMD_EXECUTE_SQL: {
                String sqlDirectoryStr = DBPropertiesUtil.getValue("flyway.sqlDirectory");
                File sqlDirectory = null;
                if (sqlDirectoryStr != null && sqlDirectoryStr.length() > 0) {
                    sqlDirectory = new File(sqlDirectoryStr);
                }
                if (sqlDirectory == null || !sqlDirectory.exists()) {
                    sqlDirectory = new File("..", "sqls");
                }
                String sqlEncoding = DBPropertiesUtil.getValue("flyway.sqlEncoding");
                oracleClient.executeSQL(sqlDirectory, sqlEncoding);
                break;
            }
            case CMD_DB_CLEAN: {
                oracleClient.flywayClean();
                break;
            }
            case CMD_DB_BASELINE: {
                String baselineVersion = DBPropertiesUtil.getValue("flyway.baselineVersion");
                String baselineDescription = DBPropertiesUtil.getValue("flyway.baselineDescription");
                oracleClient.flywayBaseline(baselineVersion, baselineDescription);
                break;
            }
        }
    }

}
